//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { Button, Card, Input, List, message, Modal, Popover, Space, Tabs } from 'antd';
import { useStores } from '@/hooks';
import type { FeedBackInfo } from "@/api/feedback";
import { add as add_feedback, list as list_feedback, remove as remvoe_feedback } from "@/api/feedback";
import { request } from '@/utils/request';
import moment from 'moment';
import { MoreOutlined } from '@ant-design/icons';
import { open as shell_open } from '@tauri-apps/api/shell';

const PAGE_SIZE = 10;

const FeedBackHistory = observer(() => {
    const userStore = useStores("userStore");

    const [feedBackInfoList, setFeedBackInfoList] = useState<FeedBackInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const loadFeedBackList = async () => {
        const res = await request(list_feedback({
            session_id: userStore.sessionId,
            offset: curPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setFeedBackInfoList(res.info_list);
        setTotalCount(res.total_count);
    };

    const removeFeedBack = async (feedBackId: string) => {
        await request(remvoe_feedback({
            session_id: userStore.sessionId,
            feed_back_id: feedBackId,
        }));
        await loadFeedBackList();
        message.info("删除成功");
    };

    useEffect(() => {
        loadFeedBackList();
    }, [curPage]);

    return (
        <List rowKey="feed_back_id" dataSource={feedBackInfoList} style={{ maxHeight: "calc(100vh - 400px)", overflowY: "scroll" }}
            pagination={{ current: curPage + 1, pageSize: PAGE_SIZE, total: totalCount, showSizeChanger: false, hideOnSinglePage: true, onChange: page => setCurPage(page - 1) }}
            renderItem={item => (
                <List.Item>
                    <Card title={moment(item.time_stamp).format("YYYY-MM-DD HH:mm")} style={{ width: "100%" }} bordered={false}
                        extra={
                            <Popover placement='bottom' trigger="click" content={
                                <Space direction='vertical'>
                                    <Button type="link" danger onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        removeFeedBack(item.feed_back_id);
                                    }}>删除</Button>
                                </Space>
                            }>
                                <MoreOutlined />
                            </Popover>
                        }>
                        <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word" }}>{item.content}</pre>
                    </Card>
                </List.Item>
            )} />
    );
});

export interface FeedBackModalProps {
    onClose: () => void;
}

const FeedBackModal = (props: FeedBackModalProps) => {
    const userStore = useStores("userStore");
    const appStore = useStores("appStore");

    const [activeKey, setActiveKey] = useState<"feedback" | "history">("feedback");
    const [content, setContent] = useState("");

    const addFeedBack = async () => {
        await request(add_feedback({
            content: content,
            session_id: userStore.sessionId,
        }));
        message.info("提交成功");
        props.onClose();
    };

    return (
        <Modal open mask={false} footer={activeKey == "feedback" ? undefined : null}
            bodyStyle={{ padding: "6px 10px" }}
            okText="提交" okButtonProps={{ disabled: content.trim() == "" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onClose();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                addFeedBack();
            }}>
            <Tabs activeKey={activeKey} onChange={key => setActiveKey(key as "feedback" | "history")}
                type='card'
                tabBarExtraContent={
                    <Space style={{ marginRight: "30px" }}>
                        {activeKey == "feedback" && (
                            <Button type="link" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                shell_open(appStore.vendorCfg?.layout.feedback_url ?? "");
                            }}>访问代码仓库issue列表</Button>
                        )}
                    </Space>
                }>
                <Tabs.TabPane key="feedback" tab="提交反馈意见">
                    {activeKey == "feedback" && (
                        <Input.TextArea autoSize={{ minRows: 5, maxRows: 5 }} value={content} onChange={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setContent(e.target.value);
                        }} />
                    )}
                </Tabs.TabPane>
                {userStore.sessionId != "" && (
                    <Tabs.TabPane key="history" tab="提交历史">
                        {activeKey == "history" && (
                            <FeedBackHistory />
                        )}
                    </Tabs.TabPane>
                )}
            </Tabs>
        </Modal>
    );
};

export default observer(FeedBackModal);